using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Expression;

namespace NDomain.ExampleModels.BloggingSystem.Infrastructure
{
    public class BlogRepositoryImpl : IBlogRepository
    {
        private ISession _session;

        public BlogRepositoryImpl(ISession session)
        {
            _session = session;
        }

        #region IBlogRepository Members

        public bool ExistsByName(string name)
        {
            return FindByName(name).Count > 0;
        }

        private IList<Blog> FindByName(string name)
        {
            return CreateCriteria()
                .Add(Expression.Eq("Name", name))
                .List<Blog>();
        }

        private ICriteria CreateCriteria()
        {
            return _session.CreateCriteria(typeof (Blog));
        }

        #endregion

        #region ICollection<Blog> Members

        public void Add(Blog item)
        {
            _session.Save(item);
        }

        public void Clear()
        {
            _session.Delete("from Blog");
        }

        public bool Contains(Blog item)
        {
            return _session.Contains(item);
        }

        public void CopyTo(Blog[] array, int arrayIndex)
        {
            FindAll().CopyTo(array, arrayIndex);
        }

        private IList<Blog> FindAll()
        {
            return CreateCriteria().List<Blog>();
        }

        public bool Remove(Blog item)
        {
            _session.Delete(item);
            return true;
        }

        public int Count
        {
            get { return FindAll().Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        #endregion

        #region IEnumerable<Blog> Members

        IEnumerator<Blog> IEnumerable<Blog>.GetEnumerator()
        {
            return ((IEnumerable<Blog>)FindAll()).GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        public IEnumerator GetEnumerator()
        {
            return FindAll().GetEnumerator();
        }

        #endregion
    }
}
